package com.newlink.building.record.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Looper
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.newlink.building.library_rino.ConnectionController
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.event.CaptureExitEditEvent
import com.newlink.building.common_base.event.EnterEditEvent
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.ScreenShotDeleteEvent
import com.newlink.building.common_base.event.ScreenShotSelectEvent
import com.newlink.building.common_base.event.TYPE_APP_SCREENSHOT_EDIT_OFF
import com.newlink.building.common_base.event.UpdateButtonEvent
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.ToastUtils
import com.newlink.building.common_base.utils.WeakHandler
import com.newlink.building.common_base.widget.CustomDialog
import com.newlink.building.common_base.widget.CustomLoadMoreView
import com.newlink.building.record.Module_Record_CaptureVideoDetailActivityNL
import com.newlink.building.record.R
import com.newlink.building.record.adapter.Module_Record_CaptureVideoAdapter
import com.newlink.building.record.databinding.FragmentCaptureVideoBinding
import com.newlink.building.record.mvp.Module_Record_CaptureVideoPresenter
import com.newlink.building.record.mvp.contract.Module_Record_CaptureVideoContract
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


data class CaptureVideoBean(var path: String, var isSelected: Boolean)

var mEditMode = false

/**
 * @author wangyang
 * @date 2022/10/8
 * @description 记录——截图记录页面
 */
class CaptureVideoFragment :
    BaseMvpFragment<Module_Record_CaptureVideoContract.View, Module_Record_CaptureVideoContract.Presenter>(),
    Module_Record_CaptureVideoContract.View {

    private val weakHandler by lazy { WeakHandler(Looper.getMainLooper()) }
    private var mAdapter: Module_Record_CaptureVideoAdapter? = null
    private var curList: MutableList<String> = ArrayList()
    private var mCaptureList: MutableList<CaptureVideoBean> = ArrayList()
    private var mEmptyContent: View? = null

    private lateinit var mBinding: FragmentCaptureVideoBinding

    override fun attachLayoutRes(): View {
        mBinding = FragmentCaptureVideoBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initView(view: View) {
        mEmptyContent = view.findViewById(R.id.empty_content)
        mBinding.swipeRefreshLayout.setOnRefreshListener {
            weakHandler.postDelayed({

                NLog.e("[CaptureVideoFragment] ...screen shot list ::>  $curList")
                loadScreenshot()
//                showToast(getString(R.string.default_list_data_refresh))
                mBinding.swipeRefreshLayout.isRefreshing = false
            }, 500)
        }
    }

    private fun loadScreenshot() {
        curList.clear()
        if (!isAdded) {
            return
        }
//        curList = VoipController.get().getAllScreenshot()!!
        curList = ConnectionController.getInstance(requireContext().applicationContext)
            .getSnapshot(requireContext()).toMutableList()
        curList.reverse()
        setCaptureList(curList)
        initAdapter(mCaptureList)
    }

    private fun setCaptureList(curList: MutableList<String>) {
        mCaptureList.clear()
        for (item in curList) {
            mCaptureList.add(CaptureVideoBean(item, false))
        }
    }


    override fun lazyLoad() {
        NLog.e("CaptureVideoFragment lazyLoad")
        loadScreenshot()
    }

    override fun onResume() {
        super.onResume()
        NLog.e("CaptureVideoFragment onResume")
        if (mCaptureList.size > 0) {
            NLog.e("CaptureVideoFragment mCaptureList size > 0 ")
        } else {
            lazyLoad()
        }
    }

    override fun hideLoading() {
        super.hideLoading()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initAdapter(list: MutableList<CaptureVideoBean>) {
        if (list.size > 0) {

            if (mAdapter == null) {
                mAdapter = Module_Record_CaptureVideoAdapter(mCaptureList)
                if (mBinding.rvCaptureVideo == null) {
                    return
                }
                mBinding.rvCaptureVideo.layoutManager = GridLayoutManager(context, 2)
                mBinding.rvCaptureVideo.adapter = mAdapter
                mAdapter?.setOnItemClickListener { adapter, view, position ->
                    if (mCaptureList.size == 0) {
                        return@setOnItemClickListener
                    }
                    if (mEditMode) {
                        mCaptureList[position].isSelected = !mCaptureList[position].isSelected
                        mAdapter?.notifyDataSetChanged()
                        updateSelectButton()
                    } else {
//                        CaptureVideoDetailActivity.startSelf(context, mCaptureList[position].path)
//                        Intent(requireContext() , mCaptureList[position].path)
                        Intent(requireContext(), Module_Record_CaptureVideoDetailActivityNL::class.java).apply {
                            putExtra("data", mCaptureList[position].path)
                            startActivityForResult(this, 11100)
                        }
                    }
                }

                mAdapter?.setOnItemLongClickListener { _, _, position ->
                    if (!mEditMode) {
                        intoEditMode()
                        mCaptureList[position].isSelected = !mCaptureList[position].isSelected
                        mAdapter?.notifyDataSetChanged()
                        updateSelectButton()
                    }
                    true
                }

                mAdapter?.run {
                    setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
                    loadMoreModule.loadMoreView = CustomLoadMoreView()
                    loadMoreModule.setOnLoadMoreListener {
                        mBinding.swipeRefreshLayout.isRefreshing = false
                        weakHandler.postDelayed({
                            loadMoreModule.loadMoreEnd()
                        }, 500)
                    }
                }
            } else {
                mAdapter?.setNewOrAddData(true, mCaptureList)
            }
        } else {
            mAdapter?.notifyDataSetChanged()
        }

        if (curList.size == 0) {
            mEmptyContent?.visibility = View.VISIBLE
            mBinding.rvCaptureVideo.visibility = View.GONE
        } else {
            mEmptyContent?.visibility = View.GONE
            mBinding.rvCaptureVideo.visibility = View.VISIBLE
        }
        hideLoading()
    }

    override fun createPresenter(): Module_Record_CaptureVideoContract.Presenter = Module_Record_CaptureVideoPresenter()

    override fun showData() {
    }

    private fun intoEditMode() {
        if (!mEditMode) {
            mEditMode = true
            NLog.e("[CaptureVideoFragment]...intoEditMode1")
            EventBus.getDefault().post(EnterEditEvent())
            mAdapter?.setEditMode(true)
            mBinding.gapView.visibility = View.VISIBLE
            mBinding.swipeRefreshLayout.isEnabled = false
        }
    }

    override fun onPause() {
        super.onPause()
        NLog.e("[CaptureVideoFragment]...onPause...")
    }

    private fun exitEditMode() {
        if (mEditMode) {
            mEditMode = false
            mAdapter?.setEditMode(false)
            mBinding.gapView.visibility = View.GONE
            mBinding.swipeRefreshLayout.isEnabled = true
            for (item in mCaptureList) {
                item.isSelected = false
            }
            EventBus.getDefault().post(CaptureExitEditEvent())
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageReceived(event: MessageEvent) {

        if (event.msgType == TYPE_APP_SCREENSHOT_EDIT_OFF) {
            NLog.e("[CaptureVideoFragment]...TYPE_APP_SCREENSHOT_EDIT_OFF")
            exitEditMode()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onScreenshotSelectEvent(event: ScreenShotSelectEvent) {
        NLog.e("jake  onExitEditEvent ${event.isSelectAll}")
        for (item in mCaptureList) {
            item.isSelected = !event.isSelectAll
        }
        mAdapter?.notifyDataSetChanged()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onScreenshotDeleteEvent(event: ScreenShotDeleteEvent) {

        NLog.e("jake onDelete selected")

        if (!hasSelected()) {
            ToastUtils.showTextToast(getString(R.string.capture_delete_unselect))
            return
        }
        showConfirmDialog()

    }

    private fun deleteSelectedImage() {
        showLoading()
        lifecycleScope.launch(Dispatchers.IO) {
            for (item in mCaptureList) {
                NLog.e("[CaptureVideoFragment]...onScreenshotDeleteEvent111 : ${item.isSelected} : ${item.path}")
                if (item.isSelected) {
//                    VoipController.get().removeScreenshot("${item.path}")
                    ConnectionController.getInstance(requireContext().applicationContext)
                        .deleteSnapshot(item.path)
                    NLog.e("[CaptureVideoFragment]...onScreenshotDeleteEvent222 : ${item.isSelected} : ${item.path}")
                }
            }
            NLog.e("[CaptureVideoFragment]...onScreenshotDeleteEvent333 ")
            withContext(Dispatchers.Main) {
                loadScreenshot()
                hideLoading()
                if (mEditMode) {
                    exitEditMode()
                }
                NLog.e("[CaptureVideoFragment]...onScreenshotDeleteEvent444 ")
            }
        }
    }

    private fun hasSelected(): Boolean {
        for ((index, item) in mCaptureList.withIndex()) {
            if (item.isSelected) {
                NLog.e("[CaptureVideoFragment]...is Select : $index")
                return true
            }
        }
        return false
    }

    private fun showConfirmDialog() {
        CustomDialog(requireContext()).setMessage(getString(R.string.dialog_delete_many_screenshot))
            .setPositiveButton(object : CustomDialog.OnClickListener {
                override fun onClick(dialog: CustomDialog) {
                    deleteSelectedImage()
                    dialog.dismiss()
                }
            }).setNegativeButton(object : CustomDialog.OnClickListener {
                override fun onClick(dialog: CustomDialog) {
                    dialog.dismiss()
                }
            }).show()
    }


    private fun updateSelectButton() {
        if (checkAllSelect()) {
            NLog.e("[CaptureVideoFragment] .. updateSelectButton ..checkAllSelect false")
            EventBus.getDefault().post(UpdateButtonEvent(false))
        } else {
            NLog.e("[CaptureVideoFragment] .. updateSelectButton ..checkAllSelect true")
            EventBus.getDefault().post(UpdateButtonEvent(true))
        }
    }

    private fun checkAllSelect(): Boolean {
        val selectList = mCaptureList.filter {
            it.isSelected
        }
        NLog.e("[CaptureVideoFragment] .. updateSelectButton ..${selectList.size}")
        if (selectList.size == mCaptureList.size) {
            return true
        }
        return false
    }


    override fun onDestroyView() {
        super.onDestroyView()
        mEditMode = false
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 11100) {
            if (resultCode == Activity.RESULT_OK) {
                NLog.e("[CaptureVideoFragment] :::  onActivityResult")
                loadScreenshot()
            }
        }
    }
}